package com.gitee.huxing.course.netty.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpResponse;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.gateway.filter
 * @ClassName: HttpBodyResponseFilter
 * @Author: huxing
 * @DateTime: 2021-08-21 下午4:24
 */
public class HttpBodyResponseFilter implements HttpResponseFilter{

    @Override
    public FullHttpResponse filter(FullHttpResponse response){
        // 获取报文内容
        String body = response.content().toString(StandardCharsets.UTF_8);
        // 转换成json对象
        JSONObject jsonObject = JSONObject.parseObject(body);
        // 在对象里面增加一个参数 - 返回消息成功
        jsonObject.put("code", "0000");
        String returBody = jsonObject.toJSONString();
        // 重新写入
        byte[] buf = returBody.getBytes(StandardCharsets.UTF_8);
        // 重设长度
        response.headers().set(CONTENT_LENGTH, buf.length);
        // 重写报文体
        return response.replace(Unpooled.wrappedBuffer(returBody.getBytes(StandardCharsets.UTF_8)));
    }
}
